package com.bml.architect.algorithms.standard;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * 精确查找
 */
public class MyPreciseDbAlgorithm implements PreciseShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Long> preciseShardingValue) {
        //逻辑表名称 如：course
        String logicTableName = preciseShardingValue.getLogicTableName();
        //分片健 如cid
        String columnName = preciseShardingValue.getColumnName();
        //值，比如select * from course where cid=3，这里的value就是3
        Long value = preciseShardingValue.getValue();
        //实现找数据库，实现inline的 m$->{cid % 2 + 1}
        BigInteger shardingValue = BigInteger.valueOf(value);
        //cid % 2 + 1
        BigInteger val = shardingValue.mod(new BigInteger("2")).add(new BigInteger("1"));
        String key = "m" + val;
        if (collection.contains(key)) {
            return key;
        }
        throw new UnsupportedOperationException("route " + key + " is not supported ,please check your config");

    }
}
